package com.example.controller;

import com.example.domain.ShoppingCart;
import com.example.service.IShoppingCartService;
import com.example.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private IShoppingCartService shoppingCartService;

    /**
     * 添加菜品到购物车
     * @param shoppingCart 购物车信息
     * @param session 存储的用户id
     * @return 响应到页面的数据
     */
    @PostMapping("/add")
    public R add(@RequestBody ShoppingCart shoppingCart, HttpSession session){
        Long user = (Long) session.getAttribute("user");
        ShoppingCart add = shoppingCartService.add(shoppingCart, user);
        return new R(1,add);
    }

    /**
     * 减少选中的菜品
     * @param shoppingCart 选中餐品的信息
     * @return 响应给页面的数据
     */
    @PostMapping("/sub")
    public R sub (@RequestBody ShoppingCart shoppingCart,HttpSession session){
        ShoppingCart sub = shoppingCartService.sub(shoppingCart,(Long)session.getAttribute("user"));
        return new R(1,sub);
    }

    /**
     * 购物车数据的展示
     * @param session 存储用户的id
     * @return 响应到页面的数据
     */
    @GetMapping("/list")
    public R list (HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        List<ShoppingCart> list = shoppingCartService.list(userId);
        return new R(1,list);
    }

    /**
     * 清空购物车
     * @param session 获取存储的用户id
     * @return 响应给页面的数据
     */
    @DeleteMapping("/clean")
    public R clean(HttpSession session){
        Long user = (Long) session.getAttribute("user");
        shoppingCartService.clean(user);
        return new R(1,"删除成功");
    }

}
